<?php
/**
 * Here is your custom functions.
 */

function success($data = [], $msg = '操作成功') {
    return ['code' => 200, 'msg' => $msg, 'data' => $data];
}

function error($msg, $data = '') {
    return ['code' => 400, 'msg' => $msg, 'data' => $data];
}

function other($code, $msg = '', $data = []) {
    return json_encode(compact('code', 'msg', 'data'));
}

const OK = 1;
const NO = 0;

function result($code, $msg = '操作成功', $data = []) {
    return compact('code', 'msg', 'data');
}

function getRandom($length, $type = 'number') {
    $str = '';
    switch ($type) {
        case 'number' :
            $str = '0123456789';
            break;
        case 'small' :
            $str = 'abcdefghjkmnpqrstuvwxyz';
            break;
        case 'big' :
            $str = 'ABCDEFGHJKMNPQRSTUVWXYZ';
            break;
        case 'invite' :
            $str = '0123456789ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
            break;
        default :
            $str = '1111111111111111';
            break;
    }

    $data = '';
    $strLength = strlen($str);
    for ( $i = 0; $i < $length; $i++ ) {
        $range = mt_rand(0, $strLength-1);
        $data.=$str[$range];
    }

    return $data;
}

function isToken($token) {
    $info = \App\user\cache\UserTokenCache::get($token);
    if (empty($info)) return false;
    return $info;
}

// 辅助功能，多维数组，转化为一维数组
function changeJson($data, $type = 'add') {
    foreach ($data as &$item) {
        switch ($type) {
            case 'add' :
                if(is_array($item))  $item = json_encode($item);
                break;
            default :
                if (json_decode($item)) $item = json_decode($item, true);
                break;
        }
    }
    return $data;
}


function uuid()
{
    return sprintf(
        '%04x%04x%04x%04x%04x%04x%04x%04x',
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff)
    );
}